﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web.Security;

namespace DataAccess.TB
{
    public class Tkl
    {
        /// <summary>
        /// 生成淘口令,需要引入System.Web.dll这个dll
        /// 使用例子:CreateTaobaoPassword.CreateToken("http://static.nut.la/coupon.jpg", "超人合伙人会员专属优惠券", "5e7b62d7640f41058d0996f99541b441", "mm_32326177_20860650_70620163", "42967846606", "3254152761", "23772858", "5f51991a8a3455f71e6d2683e5b89dbf")
        /// </summary>

        #region 生成淘口令
        /// <summary>
        /// 生成淘口令
        /// </summary>
        /// <param name="logo">显示的淘口令左边图标</param>
        /// <param name="text">显示淘口令文字内容</param>
        /// <param name="activityId">优惠券的数字ID</param>
        /// <param name="pid">推广位PID(例如:mm_32326177_20860650_70620163)</param>
        /// <param name="itemId">产品ID</param>
        /// <param name="taobaoid">宝数字id,可以为0</param>
        /// <param name="appkey">淘宝申请的appkey</param>
        /// <param name="secret">淘宝申请的secret</param>
        /// <returns>返回淘口令,如果生成失败返回string.Empty</returns>
        public static string CreateToken(string logo, string text, string activityId, string pid, string itemId, string taobaoid, string appkey, string secret)
        {
            string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string tpwd_param = string.Format("{{\"ext\":{{\"XX\":\"xx\"}},\"logo\":\"{0}\",\"text\":\"{1}\",\"url\":\"http://uland.taobao.com/coupon/edetail?activityId={2}&pid={3}&itemId={4}\",\"user_id\":\"{5}\"}}", logo, text, activityId, pid, itemId, taobaoid);
            string arg1 = "app_key" + appkey + "formatxmlmethodtaobao.wireless.share.tpwd.createsign_methodmd5timestamp" + timestamp + "tpwd_param" + tpwd_param + "v2.0";
            string md5 = MD5Encrypt(secret + arg1 + secret).ToUpper();

            string url = "http://gw.api.taobao.com/router/rest?app_key=" + appkey + "&format=xml&v=2.0&method=taobao.wireless.share.tpwd.create&sign_method=md5&timestamp=" + System.Web.HttpUtility.UrlEncode(timestamp) + "&tpwd_param=" + System.Web.HttpUtility.UrlEncode(tpwd_param) + "&sign=" + md5;
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
            WebResponse wr = null;
            StreamReader weatherStreamReader = null;
            req.Method = "GET";
            try
            {
                using (wr = req.GetResponse())
                {
                    //在这里对接收到的页面内容进行处理 
                    //读取数据流
                     weatherStreamReader = new StreamReader(wr.GetResponseStream(), System.Text.Encoding.UTF8);
                    //读取数据
                    string content = weatherStreamReader.ReadToEnd();
                    //获取淘口令
                    //Regex reg = new Regex(@"￥\w+￥");
                    //result = reg.Match(content).Value;
                    Regex reg = new Regex(@"<model>([\w\W]+)</model>");
                    MatchCollection maths = reg.Matches(content);
                    result = string.Empty;
                    if (maths.Count > 0)
                    {
                        foreach (Match mc in maths)
                        {
                            if (mc.Groups.Count == 2)
                            {
                                result = mc.Groups[1].Value;
                                break;
                            }
                        }
                    }

                }
            }
            catch (WebException e)
            {
                throw e;
            }
            finally
            {
                if (weatherStreamReader != null)
                {
                    weatherStreamReader.Close();
                }
                if (wr != null)
                {
                    wr.Close();
                }
            }
            return result;

        }
        #endregion

        private static string MD5Encrypt(string strText)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(strText, "MD5");
        }
    }
}
